<template>
  <div class="order-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">订单管理</h1>
        <p class="page-description">管理系统中的所有订单信息</p>
      </div>
      <div class="header-actions">
        <button class="btn btn-primary" @click="refreshOrders">
          <i class="fas fa-refresh"></i>
          刷新
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card pending">
          <div class="stat-icon">
            <i class="fas fa-clock"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.pending }}</div>
            <div class="stat-label">待确认订单</div>
          </div>
        </div>
        
        <div class="stat-card confirmed">
          <div class="stat-icon">
            <i class="fas fa-hourglass-half"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.confirmed }}</div>
            <div class="stat-label">待支付</div>
          </div>
        </div>
        
        <div class="stat-card paid">
          <div class="stat-icon">
            <i class="fas fa-credit-card"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.paid }}</div>
            <div class="stat-label">已支付</div>
          </div>
        </div>
        
        <div class="stat-card shipped">
          <div class="stat-icon">
            <i class="fas fa-shipping-fast"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.shipped }}</div>
            <div class="stat-label">已发货</div>
          </div>
        </div>
        
        <div class="stat-card completed">
          <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        
        <div class="stat-card cancelled">
          <div class="stat-icon">
            <i class="fas fa-times-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.cancelled }}</div>
            <div class="stat-label">已取消</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和过滤 -->
    <div class="filters-section">
      <div class="search-box">
        <div class="search-input-wrapper">
          <i class="fas fa-search search-icon"></i>
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索订单号、用户名..."
            class="search-input"
          @input="handleSearch"
          />
          <button
            v-if="searchQuery"
            class="clear-search"
            @click="clearSearch"
          >
            <i class="fas fa-times"></i>
          </button>
      </div>
    </div>

      <div class="filter-controls">
        <select v-model="statusFilter" @change="applyFilters" class="filter-select">
          <option value="">全部状态</option>
          <option value="pending">待确认订单</option>
          <option value="confirmed">待支付</option>
          <option value="paid">已支付</option>
          <option value="shipped">已发货</option>
          <option value="completed">已完成</option>
          <option value="cancelled">已取消</option>
        </select>
        
        <div class="date-filter">
          <input
            v-model="dateRange.start"
            type="date"
            class="date-input"
            placeholder="开始日期"
          />
          <span class="date-separator">至</span>
          <input
            v-model="dateRange.end"
            type="date"
            class="date-input"
            placeholder="结束日期"
          />
        </div>
      </div>
    </div>

    <!-- 悬浮批量操作按钮 -->
    <div v-if="selectedOrders.length > 0" class="floating-batch-actions">
      <div class="batch-main">
      <div class="batch-info">
          <span class="selected-count">{{ selectedOrders.length }}</span>
          <span class="selected-text">已选择</span>
      </div>
      <div class="batch-buttons">
          <button @click="showBatchMenu = !showBatchMenu" class="batch-toggle-btn" :class="{ active: showBatchMenu }">
            <i class="fas" :class="showBatchMenu ? 'fa-times' : 'fa-cog'"></i>
          </button>
      </div>
    </div>

      <!-- 批量操作菜单 -->
      <div v-if="showBatchMenu" class="batch-menu">
        <div class="batch-menu-header">
          <h4>批量操作</h4>
        </div>
        <div class="batch-menu-content">
          <div class="batch-action-group">
            <label class="action-label">状态更新</label>
            <div class="action-row">
              <select v-model="batchStatusUpdate" class="batch-status-select">
                <option value="">选择新状态</option>
                <option value="confirmed">确认订单</option>
                <option value="shipped">标记为已发货</option>
                <option value="completed">确认收货完成</option>
                <option value="cancelled">取消订单</option>
              </select>
              <button @click="batchUpdateStatus" class="btn btn-primary btn-sm" :disabled="!batchStatusUpdate">
                <i class="fas fa-edit"></i>
                更新状态
              </button>
            </div>
          </div>
          
          <div class="batch-action-group">
            <label class="action-label">危险操作</label>
            <div class="action-row">
              <button @click="batchDeleteOrders" class="btn btn-danger btn-sm btn-full">
                <i class="fas fa-trash"></i>
                批量删除订单
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-section">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span>加载订单数据中...</span>
      </div>
      
      <div v-else-if="filteredOrders.length === 0" class="empty-state">
        <i class="fas fa-shopping-cart"></i>
        <h3>{{ searchQuery || statusFilter ? '未找到匹配的订单' : '暂无订单数据' }}</h3>
        <p>{{ searchQuery || statusFilter ? '请尝试调整搜索条件' : '系统中还没有订单记录' }}</p>
      </div>
      
      <div v-else class="orders-table-container">
        <table class="orders-table">
          <thead>
            <tr>
              <th class="checkbox-column">
                <input
                  type="checkbox"
                  :checked="isAllSelected"
                  @change="toggleSelectAll"
                  class="batch-checkbox"
                />
              </th>
              <th>订单信息</th>
              <th>用户信息</th>
              <th>商品信息</th>
              <th>金额</th>
              <th>状态</th>
              <th>下单时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="order in paginatedOrders"
              :key="order.orderId"
              class="order-row"
            >
              <td class="checkbox-column">
                <input
                  type="checkbox"
                  :value="order.orderId"
                  v-model="selectedOrders"
                  class="batch-checkbox"
                />
              </td>
              
              <td class="order-info-cell">
                <div class="order-id">
                  <strong>#{{ order.orderId }}</strong>
                </div>
                <div class="order-payment">
                  {{ order.paymentMethod || '未指定' }}
                </div>
              </td>
              
              <td class="user-cell">
                <div class="user-info">
                  <div class="user-name">{{ getUserDisplayName(order) }}</div>
                  <div class="user-contact">
                    <i class="fas fa-envelope"></i>
                    {{ order.user?.email || '-' }}
                  </div>
                  <div class="user-contact">
                    <i class="fas fa-phone"></i>
                    {{ order.user?.phoneNumber || order.user?.phone || '-' }}
                  </div>
                  <div class="user-id">
                    <i class="fas fa-user"></i>
                    用户ID: {{ order.userId }}
                  </div>
                </div>
              </td>
              
              <td class="products-cell">
                <div class="products-list">
                  <div
                    v-for="detail in order.orderDetails"
                    :key="detail.detailId"
                    class="product-item"
                  >
                    <div class="product-name">{{ detail.product?.productName || '未知商品' }}</div>
                    <div class="product-quantity">x{{ detail.quantity }}</div>
                  </div>
                </div>
              </td>
              
              <td class="amount-cell">
                <div class="amount-value">¥{{ formatMoney(order.totalAmount) }}</div>
              </td>
              
              <td class="status-cell">
                <span
                  class="status-badge"
                  :class="getStatusClass(order.orderStatus)"
                >
                  {{ getStatusText(order.orderStatus) }}
                </span>
              </td>
              
              <td class="date-cell">
                {{ formatDate(order.purchaseTime) }}
              </td>
              
              <td class="actions-cell">
                <div class="action-buttons">
                  <button
                    class="btn btn-sm btn-info"
                    @click="viewOrderDetails(order)"
                    title="查看详情"
                  >
                    <i class="fas fa-eye"></i>
                  </button>
                  <button
                    class="btn btn-sm btn-primary"
                    @click="editOrder(order)"
                    title="编辑订单"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                  <div class="dropdown">
                    <button
                      class="btn btn-sm btn-warning dropdown-toggle"
                      @click="toggleDropdown(order.orderId)"
                      title="更新状态"
                      :disabled="updatingOrderId === order.orderId"
                    >
                      <i
                        class="fas"
                        :class="updatingOrderId === order.orderId ? 'fa-spinner fa-spin' : 'fa-edit'"
                      ></i>
                    </button>
                    <div
                      v-if="activeDropdown === order.orderId"
                      class="dropdown-menu"
                    >
                      <template v-if="getAvailableActions(order.orderStatus).length > 0">
                        <button
                          v-for="action in getAvailableActions(order.orderStatus)"
                          :key="action.status"
                          class="dropdown-item"
                          :class="{ 'dropdown-item-danger': action.danger }"
                          @click="updateOrderStatus(order, action.status)"
                          :disabled="updatingOrderId === order.orderId"
                        >
                          <i class="fas" :class="action.icon"></i>
                          {{ action.text }}
                        </button>
          </template>
                      <div v-else class="dropdown-item-info">
                        <i class="fas fa-info-circle"></i>
                        无可用操作
                      </div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination-container">
        <div class="pagination-info">
          显示 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredOrders.length) }} 
          共 {{ filteredOrders.length }} 条记录
        </div>
        <div class="pagination-controls">
          <button
            class="btn btn-sm btn-secondary"
            @click="goToPage(currentPage - 1)"
            :disabled="currentPage === 1"
          >
            <i class="fas fa-chevron-left"></i>
          </button>
          
          <div class="page-numbers">
            <button
              v-for="page in visiblePages"
              :key="page"
              class="btn btn-sm"
              :class="page === currentPage ? 'btn-primary' : 'btn-secondary'"
              @click="goToPage(page)"
            >
              {{ page }}
            </button>
          </div>
          
          <button
            class="btn btn-sm btn-secondary"
            @click="goToPage(currentPage + 1)"
            :disabled="currentPage === totalPages"
          >
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 订单详情模态框 -->
    <div v-if="showOrderModal" class="modal-overlay" @click="closeOrderModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>订单详情</h3>
          <button class="modal-close" @click="closeOrderModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div v-if="selectedOrder" class="order-detail-grid">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <label>订单号:</label>
                <span>#{{ selectedOrder.orderId }}</span>
              </div>
              <div class="detail-item">
                <label>下单时间:</label>
                <span>{{ formatDate(selectedOrder.purchaseTime) }}</span>
              </div>
              <div class="detail-item">
                <label>订单状态:</label>
                <span class="status-badge" :class="getStatusClass(selectedOrder.orderStatus)">
              {{ getStatusText(selectedOrder.orderStatus) }}
                </span>
              </div>
              <div class="detail-item">
                <label>订单金额:</label>
                <span class="amount-highlight">¥{{ formatMoney(selectedOrder.totalAmount) }}</span>
              </div>
              <div class="detail-item">
                <label>支付方式:</label>
                <span>{{ selectedOrder.paymentMethod || '未指定' }}</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>用户信息</h4>
              <div class="detail-item">
                <label>用户ID:</label>
                <span>{{ selectedOrder.userId }}</span>
              </div>
              <div class="detail-item">
                <label>用户名:</label>
                <span>{{ getUserDisplayName(selectedOrder) }}</span>
              </div>
              <div class="detail-item">
                <label>邮箱:</label>
                <span>{{ selectedOrder.user?.email || '-' }}</span>
              </div>
              <div class="detail-item">
                <label>手机号:</label>
                <span>{{ selectedOrder.user?.phoneNumber || selectedOrder.user?.phone || '-' }}</span>
              </div>
            </div>
            
            <div class="detail-section full-width">
              <h4>收货信息</h4>
              <div class="detail-item">
                <label>收货地址:</label>
                <span>{{ selectedOrder.shippingAddress || '-' }}</span>
              </div>
              <div class="detail-item">
                <label>联系方式:</label>
                <span>{{ selectedOrder.contactInfo || '-' }}</span>
              </div>
            </div>
            
            <div class="detail-section full-width">
              <h4>商品清单</h4>
              <div class="products-detail-list">
                <div
                  v-for="detail in selectedOrder.orderDetails"
                  :key="detail.detailId"
                  class="product-detail-item"
                >
                <div class="product-image">
                    <img
                      :src="detail.product?.productImage || '/ceholder-product.png'"
                      :alt="detail.product?.productName"
                      @error="handleImageError"
                    />
                </div>
                  <div class="product-info">
                    <div class="product-name">{{ detail.product?.productName || '未知商品' }}</div>
                    <div class="product-spec">{{ detail.product?.specParams || '-' }}</div>
        </div>
                  <div class="product-price">
                    <div class="unit-price">¥{{ formatMoney(detail.unitPrice) }}</div>
                    <div class="quantity">x{{ detail.quantity }}</div>
      </div>
                  <div class="product-subtotal">
                    ¥{{ formatMoney(detail.unitPrice * detail.quantity) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeOrderModal">
            关闭
          </button>
          <button class="btn btn-primary" @click="editOrder(selectedOrder)">
            <i class="fas fa-edit"></i>
            编辑订单
          </button>
          <button class="btn btn-primary" @click="printOrder">
            <i class="fas fa-print"></i>
            打印订单
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑订单模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content large-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑订单</h3>
          <button class="modal-close" @click="closeEditModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <form @submit.prevent="saveOrder" class="order-form">
            <div class="form-section">
              <h4>基本信息</h4>
              <div class="form-row">
                <div class="form-group">
                  <label class="form-label">订单状态</label>
                  <select v-model="editingOrder.orderStatus" class="form-select">
                    <option value="pending">待确认订单</option>
                    <option value="confirmed">待支付</option>
                    <option value="paid">已支付</option>
                    <option value="shipped">已发货</option>
                    <option value="completed">已完成</option>
                    <option value="cancelled">已取消</option>
                  </select>
                </div>
                <div class="form-group">
                  <label class="form-label">支付方式</label>
                  <input
                    v-model="editingOrder.paymentMethod"
                    type="text"
                    class="form-input"
                    placeholder="请输入支付方式"
                  />
                </div>
              </div>
            </div>
            
            <div class="form-section">
              <h4>收货信息</h4>
              <div class="form-row">
                <div class="form-group full-width">
                  <label class="form-label">收货地址</label>
                  <textarea
                    v-model="editingOrder.shippingAddress"
                    class="form-textarea"
                    placeholder="请输入收货地址"
                    rows="3"
                  ></textarea>
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label class="form-label">联系方式</label>
                  <input
                    v-model="editingOrder.contactInfo"
                    type="text"
                    class="form-input"
                    placeholder="请输入联系方式"
                  />
                </div>
              </div>
            </div>
            
            <div class="form-section">
              <h4>商品信息</h4>
              <div class="products-edit-list">
                <div
                  v-for="(detail, index) in editingOrder.orderDetails"
                  :key="detail.detailId || index"
                  class="product-edit-item"
                >
                  <div class="product-image">
                    <img
                      :src="detail.product?.productImage || '/placeholder-product.png'"
                      :alt="detail.product?.productName"
                      @error="handleImageError"
                    />
                  </div>
                  <div class="product-info">
                    <div class="product-name">{{ detail.product?.productName || '未知商品' }}</div>
                    <div class="product-spec">{{ detail.product?.specParams || '-' }}</div>
                  </div>
                  <div class="product-controls">
                    <div class="quantity-control">
                      <label>数量:</label>
                      <input
                        v-model.number="detail.quantity"
                        type="number"
                        min="1"
                        class="quantity-input"
                        @input="updateOrderTotal"
                      />
                    </div>
                    <div class="price-control">
                      <label>单价:</label>
                      <input
                        v-model.number="detail.unitPrice"
                        type="number"
                        step="0.01"
                        min="0"
                        class="price-input"
                        @input="updateOrderTotal"
                      />
                    </div>
                  </div>
                  <div class="product-subtotal">
                    小计: ¥{{ formatMoney(detail.unitPrice * detail.quantity) }}
                  </div>
                  <button
                    type="button"
                    class="btn btn-sm btn-danger"
                    @click="removeProduct(index)"
                    title="移除商品"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </div>
              <div class="order-total">
                <strong>订单总计: ¥{{ formatMoney(editingOrder.totalAmount) }}</strong>
              </div>
            </div>
          </form>
        </div>
        
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeEditModal">
            取消
          </button>
          <button 
            class="btn btn-primary" 
            @click="saveOrder"
            :disabled="saving"
          >
            <i class="fas" :class="saving ? 'fa-spinner fa-spin' : 'fa-save'"></i>
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { orderAPI } from '@/api'

// 响应式数据
    const loading = ref(false)
    const orders = ref([])
const searchQuery = ref('')
    const statusFilter = ref('')
const dateRange = reactive({
  start: '',
  end: ''
})

// 分页
    const currentPage = ref(1)
const pageSize = ref(10)

// 模态框
const showOrderModal = ref(false)
    const selectedOrder = ref(null)
const activeDropdown = ref(null)

// 编辑状态
const updatingOrderId = ref(null)
const showEditModal = ref(false)
const editingOrder = ref({})
const saving = ref(false)

// 统计数据
const stats = reactive({
  pending: 0,
  confirmed: 0,
  paid: 0,
  shipped: 0,
  completed: 0,
  cancelled: 0
})

// 批量操作
const selectedOrders = ref([])
const batchStatusUpdate = ref('')
const showBatchMenu = ref(false)

// 计算属性
    const filteredOrders = computed(() => {
  let result = orders.value

      // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(order => 
      order.orderId.toString().includes(query) ||
      order.user?.username?.toLowerCase().includes(query) ||
      order.user?.email?.toLowerCase().includes(query)
        )
      }

      // 状态过滤
      if (statusFilter.value) {
    result = result.filter(order => order.orderStatus === statusFilter.value)
  }

  // 日期过滤
  if (dateRange.start && dateRange.end) {
    result = result.filter(order => {
      const orderDate = new Date(order.purchaseTime).toISOString().split('T')[0]
      return orderDate >= dateRange.start && orderDate <= dateRange.end
    })
  }

  return result
})

const totalPages = computed(() => Math.ceil(filteredOrders.value.length / pageSize.value))

    const paginatedOrders = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredOrders.value.slice(start, end)
    })

const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  let end = Math.min(totalPages.value, start + maxVisible - 1)
  
  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1)
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const fetchOrders = async () => {
  try {
    loading.value = true
        const response = await orderAPI.getAllOrders()
        orders.value = response.orders || []
    calculateStats()
      } catch (error) {
    console.error('获取订单列表失败:', error)
    alert('获取订单列表失败')
      } finally {
        loading.value = false
      }
    }

const calculateStats = () => {
  stats.pending = orders.value.filter(order => order.orderStatus === 'pending').length
  stats.confirmed = orders.value.filter(order => order.orderStatus === 'confirmed').length
  stats.paid = orders.value.filter(order => order.orderStatus === 'paid').length
  stats.shipped = orders.value.filter(order => order.orderStatus === 'shipped').length
  stats.completed = orders.value.filter(order => order.orderStatus === 'completed').length
  stats.cancelled = orders.value.filter(order => order.orderStatus === 'cancelled').length
}

const refreshOrders = () => {
  fetchOrders()
}

const handleSearch = () => {
  currentPage.value = 1
}

const clearSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
}

const applyFilters = () => {
  currentPage.value = 1
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const viewOrderDetails = (order) => {
      selectedOrder.value = order
  showOrderModal.value = true
}

  const closeOrderModal = () => {
    showOrderModal.value = false
    selectedOrder.value = null
  }
  
  const editOrder = (order) => {
    editingOrder.value = JSON.parse(JSON.stringify(order)) // 深拷贝
    showEditModal.value = true
    showOrderModal.value = false
  }
  
  const closeEditModal = () => {
    showEditModal.value = false
    editingOrder.value = {}
  }
  
  const updateOrderTotal = () => {
    if (editingOrder.value.orderDetails) {
      editingOrder.value.totalAmount = editingOrder.value.orderDetails.reduce((total, detail) => {
        return total + (detail.unitPrice * detail.quantity)
      }, 0)
    }
  }
  
  const removeProduct = (index) => {
    if (editingOrder.value.orderDetails && editingOrder.value.orderDetails.length > 1) {
      editingOrder.value.orderDetails.splice(index, 1)
      updateOrderTotal()
    } else {
      alert('订单至少需要包含一个商品')
    }
  }
  
  const saveOrder = async () => {
    if (!editingOrder.value.orderId) {
      alert('订单信息无效')
        return
      }

    saving.value = true
    try {
      const response = await orderAPI.updateOrder(editingOrder.value.orderId, {
        orderStatus: editingOrder.value.orderStatus,
        paymentMethod: editingOrder.value.paymentMethod,
        shippingAddress: editingOrder.value.shippingAddress,
        contactInfo: editingOrder.value.contactInfo,
        totalAmount: editingOrder.value.totalAmount,
        orderDetails: editingOrder.value.orderDetails
      })
      
      if (response.success) {
        alert('订单信息更新成功')
        closeEditModal()
        await fetchOrders()
      } else {
        alert(response.message || '更新失败')
      }
      } catch (error) {
      console.error('保存订单失败:', error)
      alert('保存失败，请检查网络连接')
      } finally {
      saving.value = false
    }
  }

const getAvailableActions = (status) => {
  const actions = []
  
  // 待确认订单 - 管理员可以确认订单或取消
  if (status === 'pending') {
    actions.push({ status: 'confirmed', text: '确认订单', icon: 'fa-check-circle' })
    actions.push({ status: 'cancelled', text: '取消订单', icon: 'fa-times', danger: true })
  }
  
  // 待支付 - 等待用户支付，管理员可以取消订单
  if (status === 'confirmed') {
    actions.push({ status: 'cancelled', text: '取消订单', icon: 'fa-times', danger: true })
  }
  
  // 已支付 - 管理员可以标记为已发货
  if (status === 'paid') {
    actions.push({ status: 'shipped', text: '标记为已发货', icon: 'fa-shipping-fast' })
  }
  
  // 已发货 - 管理员可以标记为已完成（代表用户确认收货）
  if (status === 'shipped') {
    actions.push({ status: 'completed', text: '确认收货完成', icon: 'fa-check' })
  }
  
  // 删除操作 - 所有状态都可以删除（谨慎操作）
  actions.push({ status: 'delete', text: '删除订单', icon: 'fa-trash', danger: true })
  
  return actions
}

const toggleDropdown = (orderId) => {
  activeDropdown.value = activeDropdown.value === orderId ? null : orderId
}

const updateOrderStatus = async (order, newStatus) => {
  try {
    const statusMap = {
      confirmed: '待支付',
      paid: '已支付',
      shipped: '已发货',
      completed: '已完成',
      cancelled: '已取消'
    }

    console.log('正在更新订单状态:', {
      orderId: order.orderId,
      currentStatus: order.orderStatus,
      newStatus: newStatus
    })

    // 如果是删除操作
    if (newStatus === 'delete') {
      if (!confirm(`确定要删除订单 #${order.orderId} 吗？此操作不可恢复！`)) {
        return
      }
      
      updatingOrderId.value = order.orderId
      const response = await orderAPI.deleteOrder(order.orderId)
      
      if (response.success) {
        alert('订单删除成功')
        await fetchOrders()
      } else {
        alert(response.message || '订单删除失败')
      }
    } else {
      // 状态更新操作
      if (!confirm(`确定要将订单 #${order.orderId} 的状态从"${getStatusText(order.orderStatus)}"更新为"${statusMap[newStatus]}"吗？`)) {
        return
      }

      console.log('用户确认，开始调用API...')
      
      // 设置加载状态
      updatingOrderId.value = order.orderId
      
      const response = await orderAPI.updateOrderStatus(order.orderId, newStatus)
      console.log('API响应:', response)
      
      if (response.success) {
        alert('订单状态更新成功')
        // 立即更新本地数据
        order.orderStatus = newStatus
        // 重新获取数据以确保同步
        await fetchOrders()
      } else {
        alert(response.message || '订单状态更新失败')
      }
    }

    activeDropdown.value = null
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response) {
      // 服务器响应错误
      alert(`操作失败: ${error.response.data?.message || error.response.statusText}`)
    } else if (error.request) {
      // 网络错误
      alert('网络连接失败，请检查网络连接')
    } else {
      // 其他错误
      alert(`操作失败: ${error.message}`)
    }
  } finally {
    // 清除加载状态
    updatingOrderId.value = null
  }
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待确认',      // 用户创建订单但未支付
    confirmed: '待支付',       // 管理员确认订单，等待用户支付
    paid: '已支付',           // 用户已支付，等待发货
    shipped: '已发货',        // 管理员已发货，等待用户确认收货
    completed: '已完成',      // 用户确认收货，订单完成
    cancelled: '已取消',      // 用户或管理员取消订单
    'PENDING': '待确认',
    'CONFIRMED': '待支付',
    'PAID': '已支付',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
  const classMap = {
    pending: 'status-pending',
    confirmed: 'status-confirmed',
    paid: 'status-paid',
    shipped: 'status-shipped',
    completed: 'status-completed',
    cancelled: 'status-cancelled',
    unknown: 'status-unknown'
  }
  return classMap[status] || 'status-unknown'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return parseFloat(amount).toFixed(2)
}

const getUserDisplayName = (order) => {
  if (order.user && order.user.username) {
    return order.user.username
  }
  if (order.user && order.user.name) {
    return order.user.name
  }
  return `用户${order.userId}`
}

const handleImageError = (event) => {
  event.target.src = '/ceholder-product.png'
}

const printOrder = () => {
  window.print()
}

// 生命周期
onMounted(async () => {
  await nextTick()
  fetchOrders()
})

// 点击外部关闭下拉菜单和批量操作菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.dropdown')) {
    activeDropdown.value = null
  }
  if (!event.target.closest('.floating-batch-actions')) {
    showBatchMenu.value = false
  }
    }

    onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 批量操作
const batchUpdateStatus = async () => {
  if (selectedOrders.value.length === 0 || !batchStatusUpdate.value) return
  
  if (confirm(`确定要将选中的 ${selectedOrders.value.length} 项订单的状态更新为"${getStatusText(batchStatusUpdate.value)}"吗？`)) {
    try {
      const response = await orderAPI.batchUpdateOrderStatus(selectedOrders.value, batchStatusUpdate.value)
      if (response.success) {
        alert('订单状态更新成功')
        selectedOrders.value = []
        batchStatusUpdate.value = ''
        showBatchMenu.value = false
        await fetchOrders()
      } else {
        alert(response.message || '订单状态更新失败')
      }
    } catch (error) {
      console.error('批量更新订单状态失败:', error)
      alert('批量更新失败，请检查网络连接')
    }
  }
}

const batchDeleteOrders = async () => {
  if (selectedOrders.value.length === 0) return
  
  if (confirm(`确定要删除选中的 ${selectedOrders.value.length} 项订单吗？`)) {
    try {
      const response = await orderAPI.batchDeleteOrders(selectedOrders.value)
      if (response.success) {
        alert('订单删除成功')
        selectedOrders.value = []
        showBatchMenu.value = false
        await fetchOrders()
      } else {
        alert(response.message || '订单删除失败')
      }
    } catch (error) {
      console.error('批量删除订单失败:', error)
      alert('批量删除失败，请检查网络连接')
    }
  }
}

// 批量操作辅助
const isAllSelected = computed(() => selectedOrders.value.length === filteredOrders.value.length)
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedOrders.value = []
  } else {
    selectedOrders.value = filteredOrders.value.map(order => order.orderId)
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
  background: #f8f9fa;
  min-height: calc(100vh - 60px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content .page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.header-content .page-description {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  background: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-card.confirmed .stat-icon {
  background: linear-gradient(135deg, #f1c40f, #f39c12);
}

.stat-card.paid .stat-icon {
  background: linear-gradient(135deg, #3498db, #2980b9);
}

.stat-card.shipped .stat-icon {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.stat-card.completed .stat-icon {
  background: linear-gradient(135deg, #27ae60, #229954);
}

.stat-card.cancelled .stat-icon {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
}

/* 悬浮批量操作按钮 */
.floating-batch-actions {
  position: fixed;
  bottom: 30px;
  right: 30px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  border: 1px solid #e9ecef;
  overflow: hidden;
  transition: all 0.3s ease;
}

.batch-main {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-count {
  font-size: 18px;
  font-weight: 700;
  color: #3498db;
  background: #ecf4fd;
  padding: 4px 8px;
  border-radius: 8px;
  min-width: 28px;
  text-align: center;
}

.selected-text {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
}

.batch-buttons {
  position: relative;
}

.batch-toggle-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #3498db;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.3s ease;
}

.batch-toggle-btn:hover {
  background: #2980b9;
  transform: scale(1.05);
}

.batch-toggle-btn.active {
  background: #e74c3c;
  transform: rotate(90deg);
}

.batch-menu {
  border-top: 1px solid #f1f3f4;
  background: #fafbfc;
}

.batch-menu-header {
  padding: 12px 20px;
  border-bottom: 1px solid #f1f3f4;
  background: #ffffff;
}

.batch-menu-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.batch-menu-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px 20px;
}

.batch-action-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-label {
  font-size: 12px;
  font-weight: 600;
  color: #7f8c8d;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.action-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.batch-status-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 12px;
  flex: 1;
  min-width: 120px;
  background: white;
}

.btn-full {
  width: 100%;
  justify-content: center;
}

.checkbox-column {
  width: 50px;
  text-align: center;
  padding: 12px 8px;
}

.batch-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 搜索和过滤 */
.filters-section {
  background: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 300px;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 12px;
  color: #7f8c8d;
  z-index: 1;
}

.search-input {
  width: 100%;
  padding: 10px 40px 10px 40px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  background: #ffffff;
  color: #2c3e50;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.clear-search {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  color: #7f8c8d;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.clear-search:hover {
  color: #2c3e50;
  background: #ecf0f1;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-select {
  padding: 10px 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  background: #ffffff;
  color: #2c3e50;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-select:focus {
  outline: none;
  border-color: #3498db;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  padding: 10px 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  background: #ffffff;
  color: #2c3e50;
  font-size: 14px;
  transition: all 0.3s ease;
}

.date-input:focus {
  outline: none;
  border-color: #3498db;
}

.date-separator {
  color: #7f8c8d;
  font-size: 14px;
}

/* 订单列表 */
.orders-section {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #ecf0f1;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #7f8c8d;
  text-align: center;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.orders-table-container {
  overflow-x: auto;
}

.orders-table {
  width: 100%;
  border-collapse: collapse;
}

.orders-table th {
  background: #f8f9fa;
  padding: 16px 12px;
  text-align: left;
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  border-bottom: 1px solid #f1f3f4;
}

.orders-table td {
  padding: 16px 12px;
  border-bottom: 1px solid #f1f3f4;
  vertical-align: top;
}

.order-row:hover {
  background: #f8f9fa;
}

.order-info-cell {
  min-width: 120px;
}

.order-id {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.order-payment {
  font-size: 12px;
  color: #7f8c8d;
}

.user-cell {
  min-width: 150px;
}

.user-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.user-contact {
  font-size: 12px;
  color: #7f8c8d;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 2px;
}

.user-id {
  font-size: 11px;
  color: #95a5a6;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  padding: 2px 6px;
  background: rgba(149, 165, 166, 0.1);
  border-radius: 4px;
  width: fit-content;
}

.products-cell {
  min-width: 200px;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.product-name {
  flex: 1;
  font-size: 13px;
  color: #2c3e50;
}

.product-quantity {
  font-size: 12px;
  color: #7f8c8d;
  margin-left: 8px;
}

.amount-cell {
  min-width: 100px;
}

.amount-value {
  font-weight: 600;
  color: #27ae60;
  font-size: 16px;
}

.status-cell {
  min-width: 100px;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
  border: 1px solid;
}

.status-pending {
  background: rgba(243, 156, 18, 0.1);
  color: #d68910;
  border-color: rgba(243, 156, 18, 0.3);
}

.status-confirmed {
  background: rgba(241, 196, 15, 0.1);
  color: #f39c12;
  border-color: rgba(241, 196, 15, 0.3);
}

.status-paid {
  background: rgba(52, 152, 219, 0.1);
  color: #2980b9;
  border-color: rgba(52, 152, 219, 0.3);
}

.status-shipped {
  background: rgba(155, 89, 182, 0.1);
  color: #8e44ad;
  border-color: rgba(155, 89, 182, 0.3);
}

.status-completed {
  background: rgba(39, 174, 96, 0.1);
  color: #229954;
  border-color: rgba(39, 174, 96, 0.3);
}

.status-cancelled {
  background: rgba(231, 76, 60, 0.1);
  color: #c0392b;
  border-color: rgba(231, 76, 60, 0.3);
}

.status-unknown {
  background: rgba(149, 165, 166, 0.1);
  color: #7f8c8d;
  border-color: rgba(149, 165, 166, 0.3);
}

.date-cell {
  min-width: 140px;
  font-size: 13px;
  color: #7f8c8d;
}

.actions-cell {
  min-width: 120px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-toggle {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: #ffffff;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  z-index: 1000;
  min-width: 160px;
  padding: 8px 0;
  margin-top: 4px;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 8px 16px;
  background: none;
  border: none;
  color: #2c3e50;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: left;
}

.dropdown-item:hover {
  background: #f8f9fa;
  color: #3498db;
}

.dropdown-item-danger:hover {
  background: rgba(231, 76, 60, 0.05);
  color: #c0392b;
}

.dropdown-item-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  color: #7f8c8d;
  font-size: 14px;
  font-style: italic;
}

.dropdown-item:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #95a5a6;
}

.dropdown-item:disabled:hover {
  background: none;
  color: #95a5a6;
}

.dropdown-item i {
  width: 16px;
  text-align: center;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #f1f3f4;
}

.pagination-info {
  color: #7f8c8d;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  line-height: 1.5;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #ecf0f1;
  color: #7f8c8d;
}

.btn-secondary:hover:not(:disabled) {
  background: #d5dbdb;
}

.btn-success {
  background: #27ae60;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #229954;
  transform: translateY(-1px);
}

.btn-warning {
  background: #f39c12;
  color: white;
}

.btn-warning:hover:not(:disabled) {
  background: #e67e22;
  transform: translateY(-1px);
}

.btn-danger {
  background: #e74c3c;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #c0392b;
  transform: translateY(-1px);
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-info:hover:not(:disabled) {
  background: #138496;
  transform: translateY(-1px);
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
  max-width: 90vw;
  max-height: 90vh;
  overflow: auto;
  width: 800px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f1f3f4;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.modal-close {
  background: none;
  border: none;
  color: #7f8c8d;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.modal-close:hover {
  color: #2c3e50;
  background: #ecf0f1;
}

.modal-body {
  padding: 20px;
}

.order-detail-grid {
  display: grid;
  gap: 24px;
}

.detail-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.detail-section.full-width {
  grid-column: 1 / -1;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 2px solid #f1f3f4;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item label {
  color: #7f8c8d;
  font-size: 14px;
  font-weight: 500;
  min-width: 80px;
}

.detail-item span {
  color: #2c3e50;
  font-size: 14px;
  text-align: right;
}

.amount-highlight {
  font-weight: 600;
  color: #27ae60;
  font-size: 16px;
}

.products-detail-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #f1f3f4;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.product-spec {
  font-size: 12px;
  color: #7f8c8d;
}

.product-price {
  text-align: center;
  min-width: 80px;
}

.unit-price {
  font-size: 14px;
  color: #2c3e50;
  margin-bottom: 2px;
}

.quantity {
  font-size: 12px;
  color: #7f8c8d;
}

.product-subtotal {
  font-weight: 600;
  color: #27ae60;
  font-size: 16px;
  min-width: 80px;
  text-align: right;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f1f3f4;
}

/* 编辑表单样式 */
.large-modal .modal-content {
  max-width: 900px;
  max-height: 90vh;
  overflow-y: auto;
}

.order-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-section {
  border: 1px solid #f1f3f4;
  border-radius: 8px;
  padding: 20px;
  background: #fafbfc;
}

.form-section h4 {
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 2px solid #e1e5e9;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 16px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.form-input,
.form-select,
.form-textarea {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #ffffff;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.products-edit-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-edit-item {
  display: grid;
  grid-template-columns: 60px 1fr auto auto auto;
  gap: 16px;
  align-items: center;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
}

.product-edit-item .product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  background: #f8f9fa;
}

.product-edit-item .product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-edit-item .product-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-edit-item .product-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.product-edit-item .product-spec {
  font-size: 12px;
  color: #7f8c8d;
}

.product-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 120px;
}

.quantity-control,
.price-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-control label,
.price-control label {
  font-size: 12px;
  color: #7f8c8d;
  min-width: 40px;
}

.quantity-input,
.price-input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.product-subtotal {
  font-size: 14px;
  font-weight: 500;
  color: #27ae60;
  text-align: right;
  min-width: 100px;
}

.order-total {
  text-align: right;
  padding: 16px;
  background: #ffffff;
  border: 2px solid #3498db;
  border-radius: 8px;
  margin-top: 16px;
  font-size: 16px;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-management {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .filters-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    min-width: auto;
  }

  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .date-filter {
    justify-content: space-between;
  }

  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }

  .orders-table th,
  .orders-table td {
    padding: 12px 8px;
    font-size: 13px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .action-buttons .btn {
    width: 100%;
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: center;
  }

  .modal-content {
    width: 95%;
    margin: 0 auto;
  }

  .product-detail-item {
    flex-direction: column;
    text-align: center;
  }

  .product-price,
  .product-subtotal {
    text-align: center;
  }
}

@media (max-width: 576px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .orders-table {
    font-size: 12px;
  }

  .orders-table th,
  .orders-table td {
    padding: 8px 4px;
  }

  .page-numbers {
    display: none;
  }
}
</style> 